package com.hzit.controller;

import com.hzit.entity.Classes;
import com.hzit.entity.PageResult;
import com.hzit.entity.R;
import com.hzit.service.ClassesService;
import com.hzit.service.StudentService;
import com.hzit.vo.StudentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Controller
@RequestMapping("/student")
public class StudentController {
	@Autowired
	private StudentService studentService;
	@Autowired
	private ClassesService classesService;

	//1. 查询所有学生列表
	@GetMapping("/list")
	public String findAll(Model model){
		//1.1 查询得到当前学生列表
		List<StudentVo> studentVoList = studentService.findAll();
		//1.2 将学生列表放到model中
		PageResult<StudentVo> pr = new PageResult<>();
		pr.setRows(studentVoList);
		model.addAttribute("pr",pr);
		//1.3 返回逻辑视图
		return "student/list";
	}

	//2. 分页查询
	@GetMapping("/findByPage")
	public String findByPage(@RequestParam(value = "page",defaultValue = "1") Integer page,
	                         @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
	                         Model model){
		//2.1 分页查询得到查询结果集对象
		PageResult<StudentVo> pr = studentService.findByPage(page,pageSize);
		model.addAttribute("pr",pr);
		//2.2 查询出班级列表并到model中
		List<Classes> classes = classesService.findAll();
		model.addAttribute("classes",classes);
		//2.3 返回视图
		return "student/list";
	}

	//3. 条件查询带分页
	//@ResponseBody与@RequestBody区别：
	//① 前者是将Java对象转成JSON字符串并输出
	//② 后者是将前端传入的JSON对象转换java对象
	@RequestMapping("/search")
	public String search(@RequestParam(value = "page",defaultValue = "1") Integer page,
	                @RequestParam(value = "pageSize",defaultValue = "2") Integer pageSize,
	                StudentVo vo,Model model){
		//3.1 开始条件带分页查询
		PageResult<StudentVo> pr = studentService.search(page,pageSize,vo);
		model.addAttribute("pr",pr);
		//3.2 查询出班级列表并到model中
		List<Classes> classes = classesService.findAll();
		model.addAttribute("classes",classes);
		//3.3 为了在前端限时回显用户查询的信息，可以将传入的vo对象重新放回到model中
		model.addAttribute("vo",vo);
		//3.3 返回视图
		return "student/list";
	}

	//4. 添加学生
	@PostMapping("/add")
	public String add(StudentVo vo){
		System.out.println("vo = " + vo);
		//4.1 添加学生
		studentService.add(vo);
		//4.2 返回视图
		return "redirect:/student/search.do";
	}

	//5. 修改学生
	@PostMapping("/update")
	public String update(StudentVo vo){
		studentService.update(vo);
		return "student/list";
	}

	//6. 删除学生
	@GetMapping("/delete")
	public String delete(Integer[] sids){
		studentService.delete(sids);
		return "student/list";
	}

}
